package no.ntnu.fp.handlers;

import java.io.IOException;
import java.net.ConnectException;

import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.NetworkException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.AddOrUpdateAppointmentMessage;
import no.ntnu.fp.messages.impl.AddOrUpdateAppointmentMessage.UpdateType;
import no.ntnu.fp.messages.impl.AppointmentAddedOrUpdatedMessage;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.server.MainConnection;
import no.ntnu.fp.services.AppointmentService;

public class AddOrUpdateAppointmentHandler implements Handler {
	private final AppointmentService appointmentService;
	
	public AddOrUpdateAppointmentHandler(AppointmentService appointmentService) {
		this.appointmentService = appointmentService;
	}

	@Override
	public void handleMessage(Message message) {
		AddOrUpdateAppointmentMessage addAppointmentMessage = (AddOrUpdateAppointmentMessage)message;
		
		Appointment newAppointment = null;
		UpdateType updateType = addAppointmentMessage.getUpdateType();
		switch (updateType) {
		case ADD:
			newAppointment = appointmentService.addAppointment(
										addAppointmentMessage.getAppointment());
			break;
		case UPDATE:
			newAppointment = appointmentService.updateAppointment(
										addAppointmentMessage.getAppointment());
			break;
		default:
			throw new UnsupportedOperationException(
			"Unsupported update type: "	+ updateType);	
		}
		
		
		Employee emp = newAppointment.getEmployee();
		Connection connection = MainConnection.getConnection(emp);
		
		Message reply = new AppointmentAddedOrUpdatedMessage(newAppointment);
		try {
			connection.send(reply.toString());
		} catch (IOException e) {
			throw new NetworkException("Unable to send reply", e);
		}
		
	}
}
